home *** CD-ROM | disk | FTP | other *** search
/ MacHack 2000 / MacHack 2000.toast / pc / The Hacks / MacHacksBug / Python 1.5.2c1 / Demo / comparisons / systemtest.py < prev   
Encoding:
Python Source  |  2000-06-23  |  1.9 KB  |  75 lines

  1. #! /usr/bin/env python
  2.  
  3. # 3)  System Test
  4. #     Given a list of directories, report any bogus symbolic links contained
  5. #     anywhere in those subtrees.  A bogus symbolic link is one that cannot
  6. #     be resolved because it points to a nonexistent or otherwise
  7. #     unresolvable file.  Do *not* use an external find executable.
  8. #     Directories may be very very deep.  Print a warning immediately if the
  9. #     system you're running on doesn't support symbolic links.
  10.  
  11. # This implementation:
  12. # - takes one optional argument, using the current directory as default
  13. # - uses chdir to increase performance
  14. # - sorts the names per directory
  15. # - prints output lines of the form "path1 -> path2" as it goes
  16. # - prints error messages about directories it can't list or chdir into
  17.  
  18. import os
  19. import sys
  20. from stat import *
  21.  
  22. def main():
  23.     try:
  24.         # Note: can't test for presence of lstat -- it's always there
  25.         dummy = os.readlink
  26.     except AttributeError:
  27.         print "This system doesn't have symbolic links"
  28.         sys.exit(0)
  29.     if sys.argv[1:]:
  30.         prefix = sys.argv[1]
  31.     else:
  32.         prefix = ''
  33.     if prefix:
  34.         os.chdir(prefix)
  35.         if prefix[-1:] != '/': prefix = prefix + '/'
  36.         reportboguslinks(prefix)
  37.     else:
  38.         reportboguslinks('')
  39.  
  40. def reportboguslinks(prefix):
  41.     try:
  42.         names = os.listdir('.')
  43.     except os.error, msg:
  44.         print "%s%s: can't list: %s" % (prefix, '.', msg)
  45.         return
  46.     names.sort()
  47.     for name in names:
  48.         if name == os.curdir or name == os.pardir:
  49.             continue
  50.         try:
  51.             mode = os.lstat(name)[ST_MODE]
  52.         except os.error:
  53.             print "%s%s: can't stat: %s" % (prefix, name, msg)
  54.             continue
  55.         if S_ISLNK(mode):
  56.             try:
  57.                 os.stat(name)
  58.             except os.error:
  59.                 print "%s%s -> %s" % \
  60.                       (prefix, name, os.readlink(name))
  61.         elif S_ISDIR(mode):
  62.             try:
  63.                 os.chdir(name)
  64.             except os.error, msg:
  65.                 print "%s%s: can't chdir: %s" % \
  66.                       (prefix, name, msg)
  67.                 continue
  68.             try:
  69.                 reportboguslinks(prefix + name + '/')
  70.             finally:
  71.                 os.chdir('..')
  72.  
  73. main()
  74.